#  pip install pyserial



import serial
import json
from time import sleep
import threading
from com_data import weather_mgr

# 配置串口参数
PORT = 'COM3'        # 串口号（Windows）或 '/dev/ttyUSB0'（Linux）
BAUDRATE = 115200      # 波特率需与设备一致
TIMEOUT = 1          # 读取超时时间（秒）
def loopFunGetData():
    try:
        # 初始化串口连接
        ser = serial.Serial(port=PORT, baudrate=BAUDRATE, timeout=TIMEOUT)
        print(f"已连接串口：{PORT}")

        buffer = bytearray()  # 缓存数据，应对分包情况

        while True:
            # 读取数据
            data = ser.read_all()
            if data:
                buffer += data

                # 查找JSON起始和结束标志（假设数据以{}包裹）
                start = buffer.find(b'{')
                end = buffer.find(b'}')

                if start != -1 and end != -1 and end > start:
                    # 提取完整JSON数据
                    json_data = buffer[start:end+1]
                    buffer = buffer[end+1:]  # 清除已处理数据

                    try:
                        # 解析JSON
                        parsed = json.loads(json_data.decode('utf-8'))
                        t = parsed.get("t")
                        h = parsed.get("h")
                        w = parsed.get("w")
                        l = parsed.get("l")
                        print()
                        # 打印结果（可替换为业务逻辑）
                        print(f"解析结果：t={t}, h={h}, w={w}, l={l}  ", json_data.decode('utf-8'))
                        weather_mgr.add_data(temp = t, humi = h, pres = 0, w_dir = 0, w_speed = 0) # 气温 湿度 气压 风向 风速


                    except json.JSONDecodeError:
                        print(json_data)
                        print(json_data.decode('utf-8'))
                        print("JSON解析失败：数据格式错误")
                    except KeyError as e:
                        print(f"字段缺失：{e}不存在")

            sleep(0.1)  # 降低CPU占用

    except serial.SerialException as e:
        print(f"串口连接失败：{e}")
    except KeyboardInterrupt:
        print("程序已终止")
    finally:
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("串口已关闭")

if __name__ == '__main__':
    try:
        thread = threading.Thread(target=loopFunGetData)
        thread.start()
    except:
        print("Error: unable to start thread")
    while 1:
        pass